<script setup lang="ts">
import { ContentWrapNoHeaderLine } from '@/components/ContentWrap'
import { useIcon } from '@/hooks/web/useIcon'
import { Table } from '@/components/Table'
import {
  ElForm,
  ElFormItem,
  ElSelect,
  ElOption,
  ElInput,
  ElButton,
  ElSpace,
  ElDivider,
  ElDropdown,
  ElDropdownMenu,
  ElDropdownItem,
  ElCheckbox, ElMessage
} from 'element-plus'
import { reactive, ref, h, watch, unref } from 'vue'
import { useTable } from "@/hooks/web/useTable";
import { RoleData, RoleMenuData } from "@/api/auth/role/types";
import { getRoleDetailApi, saveOrUpdate, delRoleApi, getRoleListApi, getPermission } from "@/api/auth/role/index";
import { Pagination, TableColumn } from "@/types/table";
import Edit from "./edit.vue";
import { Dialog } from '@/components/Dialog'
import { FormSchema } from "@/types/form";
import { useValidator } from "@/hooks/web/useValidator";

const { required } = useValidator()

const queryModel = reactive<Recordable>({
  column: '',
  val: '',
})

const statusOptions = [
  { label: '禁用', value: 0 },
  { label: '启用', value: 1 }
]

const columns = reactive<TableColumn[]>([
  {
    field: 'id',
    label: '权限ID',
    search: true,
    visible: true,
    className: ''
  }, {
    field: 'name',
    label: '权限',
    search: true,
    visible: true,
    className: ''
  }, {
    field: 'status',
    label: '状态',
    visible: true,
    className: ''
  }, {
    field: 'action',
    label: '操作',
    visible: true,
    className: ''
  }
])

const { register, tableObject, methods } = useTable<RoleData>({
  getListApi: getRoleListApi,
  delListApi: delRoleApi,
  response: {
    list: 'list',
    total: 'total'
  }
})
const paginationObj = ref<Pagination>()
watch(() => tableObject.total,
  (val) => {
    if (val > 0) {
      paginationObj.value = {
        total: tableObject.total
      }
    } else {
      paginationObj.value = undefined
    }
  })
const { getList, setSearchParams } = methods
getList()

const icons = {
  plusIcon: useIcon({ icon: 'ph:plus-bold' }),
  deleteIcon: useIcon({ icon: 'ep:delete' })
}
const spacer = h(ElDivider, { direction: 'vertical' })

const handleQuery = () => {
  let queryParams: Recordable = {} as any
  if (queryModel.column) {
    queryParams[queryModel.column] = queryModel.val
  }
  setSearchParams({ queryParams })
}

const selectedCount = ref(0)
const multipleSelection = ref<RoleData[]>([])
const handleSelectionChange = (val: RoleData[]) => {
  multipleSelection.value = val
  selectedCount.value = val?.length || 0
}

const handleVisibleChange = (item) => {
  item.className = item.visible ? '' : 'hidden'
}

const dialogVisible = ref(false);
const dialogTitle = ref("");
const actionType = ref("");
const loading = ref(false)
const delLoading = ref(false)
const editRef = ref<ComponentRef<typeof Edit>>()
const save = async () => {
  const role = unref(editRef)
  await role?.elFormRef?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true
      const data = (await role?.getFormData()) as RoleData
      data.permission = role.getCheckedMenu().join(",");
      const isUpdate = actionType.value == 'edit';
      const res = await saveOrUpdate(data, isUpdate)
        .catch(() => {
        })
        .finally(() => {
          loading.value = false
        })
      if (res) {
        dialogVisible.value = false
        tableObject.page_index = 1
        getList()
      }
    }
  })
}
const handleAddDomain = () => {
  tableObject.currentRow = null
  actionType.value = ''
  dialogTitle.value = '新增角色'
  dialogVisible.value = true
}
const handleEditButton = (row: RoleData) => {
  getRoleDetailApi(row.id).then(res => {
    tableObject.currentRow = res.data;
      actionType.value = 'edit';
      dialogTitle.value = '修改角色';
      dialogVisible.value = true;
  }).catch(() => {
    ElMessage.error("加载数据失败，请联系管理员！");
  });

}
const handleDeleteButton = async (row: RoleData | null, multiple: boolean) => {
  tableObject.currentRow = row
  const { delListByObj, getSelections } = methods
  const selections = await getSelections()
  delLoading.value = true
  await delListByObj(
    multiple ? selections : [row] as RoleData[],
    multiple
  ).finally(() => {
    delLoading.value = false
  })
}
const formSchema = reactive<FormSchema[]>([
  {
    field: 'name',
    label: '角色名称',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 8
    }
  },
  {
    field: 'status',
    label: '状态',
    component: 'Switch',
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 24
    },
    componentProps: {
      activeValue: statusOptions[1].value,
      activeText: statusOptions[1].label,
      inactiveText: "",
      inactiveValue: statusOptions[0].value
    },
  },
  {
    field: 'permission',
    label: '授权',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 24
    }
  }
]);

const handleReset = () => {
  const edit = unref(editRef)
  edit?.elFormRef?.resetFields()
}
</script>

<template>
  <ContentWrapNoHeaderLine title="角色管理">
    <div class="flex justify-between">
      <el-form :inline="true" ref="queryFormRef" :model="queryModel">
        <el-form-item>
          <el-space direction="horizontal" :size="0">
            <el-select v-model="queryModel.column" placeholder="请选择查询字段">
              <template v-for="col in columns">
                <el-option v-if="col.search" :label="`按${col.label}`" :key="col.field" :value="`${col.field}`" />
              </template>
            </el-select>
            <el-input v-model="queryModel.val" placeholder="请输入">
              <template #append>
                <el-button class="query-button" type="primary" @click="handleQuery">查询</el-button>
              </template>
            </el-input>
          </el-space>
        </el-form-item>
      </el-form>
      <el-button :icon="icons.plusIcon" type="primary" @click="handleAddDomain">新增角色</el-button>
    </div>
    <div class="rounded bg-gray-100 w-full flex justify-between px-1.5 py-2 mb-3.5">
      <el-space :size="10" :spacer="spacer">
        <div>已批量选择<span class="mx-1 text-[var(--el-color-primary)]">{{ selectedCount }}</span>条事项</div>
        <el-button :icon="icons.deleteIcon" link @click="handleDeleteButton(null, true)">批量删除</el-button>
      </el-space>
      <el-space :size="10">
        <el-dropdown trigger="click" :hide-on-click="false">
          <span class="el-dropdown-link">
            <Icon icon="icon-park-outline:config" class="cursor-pointer " />
          </span>
          <template #dropdown>
            <div class="flex flex-col p-2">
              <template v-for="column in columns">
                <el-checkbox v-if="column.field !== 'action'" v-model="column.visible" :label="column.label"
                  :key="column.field" size="small" @change="handleVisibleChange(column)" />
              </template>
            </div>
          </template>
        </el-dropdown>
        <el-dropdown trigger="click">
          <span class="el-dropdown-link">
            <Icon icon="bi:download" class="cursor-pointer " />
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item>导出到Csv</el-dropdown-item>
              <el-dropdown-item>导出到Excle</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <Icon icon="bi:printer" class="cursor-pointer " />
      </el-space>
    </div>
    <div class="">
      <Table border v-model:pageSize="tableObject.page_size" v-model:currentPage="tableObject.page_index"
        :columns="columns" :data="tableObject.tableList" :loading="tableObject.loading" :pagination="paginationObj"
        @register="register" @select="handleSelectionChange" @select-all="handleSelectionChange">
        <template #status="{ row }">
          <template v-for="st in statusOptions">
            <template v-if="row.status == st.value">
              {{ st.label }}
            </template>
          </template>
        </template>
        <template #action="{ row }">
          <el-space :size="6" :spacer="spacer">
            <ElButton type="primary" link @click="handleEditButton(row)">
              编辑
            </ElButton>
            <!-- <ElButton type="primary" link @click="handleEditButton(row)">
              授权
            </ElButton> -->
            <ElButton type="primary" link @click="handleDeleteButton(row, false)">
              删除
            </ElButton>
          </el-space>
        </template>
      </Table>
    </div>
  </ContentWrapNoHeaderLine>
  <Dialog v-model="dialogVisible" :title="dialogTitle" :width="'90%'" :max-height="768" :top="'1vh'">
    <Edit :action-type="actionType" ref="editRef" :form-schema="formSchema" :current-row="tableObject.currentRow"/>

    <template #footer>
      <ElButton @click="handleReset">重置</ElButton>
      <ElButton type="primary" :loading="loading" @click="save">
        提交
      </ElButton>
    </template>
  </Dialog>
</template>
